package com.starblink.wishlist.wishlistdetails.ui

import com.alibaba.android.arouter.facade.annotation.Route
import com.starblink.basic.route.RoutePage
import com.starblink.android.basic.base.activity.BaseTVMActivity
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.starblink.android.basic.const.NavParamsKeyConst
import com.starblink.android.basic.ext.*
import com.starblink.basic.apollo.ext.ApolloValSetExt.apolloValue
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.android.basic.sensorsdata.extension.trackData
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.util.post.CommonMutateManage
import com.starblink.android.basic.widget.ConfirmDialog
import com.starblink.basic.util.ActivityStackManage
import com.starblink.library.widget.wishlist.WishlistAddBottomDialog
import com.starblink.library.widget.wishlist.WishlistRenameBottomDialog
import com.starblink.library.widget.wishlist.bean.BatchProductArrEntry
import com.starblink.library.widget.wishlist.bean.WishlistRenameEntry
import com.starblink.rocketreserver.fragment.ProductF
import com.starblink.rocketreserver.fragment.WishListF
import com.starblink.share.view.ShareDialog
import com.starblink.share.view.utils.ShareTypeEnum
import com.starblink.share.view.utils.ShareUrlUtils
import com.starblink.wishlist.databinding.*
import com.starblink.wishlist.wishboards.ui.bean.RvBoardProductEntry
import com.starblink.wishlist.wishboards.ui.bean.RvNoBoardsEntry
import com.starblink.wishlist.wishlistdetails.ui.bean.RvBoardDetailsItemEntry
import com.starblink.wishlist.wishlistdetails.ui.part.WishDetailsPart

/**
 *
 * @note
 * H5跳转：传入心愿单ID 和 USER_ID
 * 原生跳转：传入心愿单对象，USER_ID，IS_MASTER，USER_IMG，USER_NAME
 * @note
 * 从H5跳转而来，需要调用接口获取心愿单详情，用户信息
 */
@Route(path = RoutePage.Wishlist.WISHLIST_DETAILS)
class WishlistDetailsActivity :
    BaseTVMActivity<ActivityWishlistDetailsBinding, WishlistDetailsVM>() {

    @Autowired(name = NavParamsKeyConst.WISHLIST_USER_ID)
    @JvmField
    var userId: String? = null //H5外链携带过来的userId app内传参也会传过来

    @Autowired(name = NavParamsKeyConst.WISHLIST_ID)
    @JvmField
    var h5WishListId: String? = null //H5外链携带过来的心愿单id 不为空时需要调用接口获取心愿单详情

    @Autowired(name = NavParamsKeyConst.WISHLIST_BOARD_ITEM)
    @JvmField
    var boardItemData: WishListF? = null

    @Autowired(name = NavParamsKeyConst.WISHLIST_USER_IMG)
    @JvmField
    var headUrl: String? = null

    @Autowired(name = NavParamsKeyConst.WISHLIST_USER_NAME)
    @JvmField
    var userName: String? = null

    @Autowired(name = NavParamsKeyConst.WISHLIST_IS_MASTER)
    @JvmField
    var isSelf: Boolean = false

    lateinit var allItemsPart: WishDetailsPart
    private var choiceMode = false

    override fun initViewBinding(): ActivityWishlistDetailsBinding =
        ActivityWishlistDetailsBinding.inflate(layoutInflater)


    private fun isFromH5() = h5WishListId != null

    override fun initData() {
        super.initData()
        if (isFromH5()) {
            isSelf = UserDataCenter.getAccountInfo()?.id == userId
            viewModel.mWishlistId = h5WishListId
            viewModel.mAccountId = userId
        }
    }

    override fun initView() {
        super.initView()
        if (isFromH5()) {
            // H5跳转：等待数据加载
        } else {
            pageExposure(SpmPageDef.WishListRoute)
            // 原生跳转：直接初始化
            initViewOfUserInfo()
            initViewOfOthers()
        }
    }

    private fun initViewOfOthers() {
        boardItemData?.let {
            //标题
            viewBinding.boardTitle.text = it.title
            viewBinding.boardTitleSave.text = it.title
            //描述
            if (it.description.isNullOrEmpty()) {
                viewBinding.boardDesc.gone()
            } else {
                viewBinding.boardDesc.visible()
                viewBinding.boardDesc.text = it.description
            }
            //总数
            viewBinding.boardItemNum.text = viewModel.refreshItemsNum(true, it.productCount)
            //点击分享
            viewBinding.boardDetailsShare.click {
                // 分享
                userId?.let { uId ->
                    ShareDialog(
                        mActivity,
                        ShareUrlUtils().getWishlistBoardsDetailShareUrl(uId, boardItemData?.id),
                        shareCome = ShareTypeEnum.WISHLIST_BOARDS_SHARE
                    ) {}.show(supportFragmentManager, "share")
                }
            }

            //是否显示设置
            viewBinding.ivSetting.visibleOrGone(isSelf && it.productCount > 0) {
                click {
                    choiceMode = !choiceMode
                    intoMutiSelect(choiceMode)
                    if (choiceMode) {
                        clickRightTopSetting()
                    }
                }
            }
            viewBinding.mutiChoiceMode.click {
                resetAllMuti(click = true)
            }

            viewBinding.floatAddBtn.visibleOrGone(isSelf) {
                trackData(
                    page = SpmPageDef.WishListRoute,
                    element = SpmElementDef.Element_33064,
                    onlyHit = true
                )

                click {
                    navigationTo(url = RoutePage.Wishlist.DETAILS_ADD) {
                        withString(NavParamsKeyConst.WISHLIST_ID, boardItemData!!.id)
                    }
                }
            }

            //是否显示编辑模式
            viewBinding.boardEdit.visibleOrGone(isSelf) {
                viewBinding.boardTitleSave.gone()
                viewBinding.boardTitle.visible()

                click {
                    WishlistRenameBottomDialog.showWishlistRenameDialog(
                        mActivity,
                        id = boardItemData!!.id,
                        title = boardItemData!!.title,
                        desc = boardItemData!!.description ?: ""
                    )
                }
            }

            //是否显示保存按钮
            viewBinding.btnSave.visibleOrGone(!isSelf) {
                viewBinding.boardTitle.gone()
                viewBinding.boardTitleSave.visible()
                updateSaveBtn(boardItemData?.collectStatus == true)
                viewBinding.btnSave.click {
                    boardItemData?.let { wishlist ->
                        updateSaveBtn(!wishlist.collectStatus)
                        SkGqlClient.defaultLoadingShow(true)
                        CommonMutateManage.collectWishlist(
                            context = context,
                            wishList = wishlist,
                        ) {
                            SkGqlClient.defaultLoadingDismiss(true)
                            if (it) {
                                // 收藏或取消收藏成功，更新数据
                                wishlist.apolloValue(
                                    "collectStatus",
                                    !wishlist.collectStatus
                                )
                            } else {
                                // 收藏或取消收藏失败，恢复UI状态
                                updateSaveBtn(wishlist.collectStatus)
                            }
                        }
                    }
                }
            }

            //初始化列表数据
            viewModel.initSomeData(boardItemData, userId)
            allItemsPart = WishDetailsPart(
                isSelf = isSelf,
                wishListId = it.id,
                viewBinding = viewBinding,
                viewModel = viewModel
            ).apply {
                handleVM()
            }

            //下拉刷新
            //不绑定state 单独处理
            viewBinding.state.refreshing()
            viewBinding.page.onMutRefresh {
                viewModel.initRefresh(hasFinish = {
                    viewBinding.state.showContent()
                    viewBinding.page.finishRefresh()
//                    //是否开启加载更多
//                    if (viewModel.mBoardsObserver.value!!.size > 3) {
//                        viewBinding.page.setEnableLoadMore(true)
//                    } else {
//                        viewBinding.page.setEnableLoadMore(false)
//                    }
                })
            }.refresh()

            //上拉加载
            viewBinding.page.onMutLoadMore {
                if (viewModel.autoLoadMoreGuess) {
                    viewModel.loadMoreGuess(hasFinish = {
                        viewBinding.page.finishLoadMore()
                    })
                } else {
                    viewModel.loadMoreWishList(hasFinish = {
                        viewBinding.page.finishLoadMore()
                    })
                }
            }

            setMutiView()

            // 先将列表控件相关初始化完成，在执行本方法
            // 注意：为防止重复注册，wishlistLiveData使用一次性LiveData
            viewModel.mAllItemsObserver.observe(this) {
                showOrHideSetting(it)

                if (viewModel.pageTopIndex == 1) {

                }

            }
        }
    }

    override fun initObservable() {
        super.initObservable()
        initFlowEvents()

        viewModel.wishlistLiveData.observe(this) {
            boardItemData = it
            initViewOfOthers()
        }

        viewModel.userInfoLiveData.observe(this) {
            userName = it.username ?: it.userName
            headUrl = it.headImage
            initViewOfUserInfo()
        }
    }

    override fun initLoad() {
        super.initLoad()
        if (isFromH5()) {
            // H5跳转：加载数据加载
            viewModel.getWishlistAndUserInfo(h5WishListId!!, userId)
        }
    }

    private fun initFlowEvents() {
        //单个推荐添加心愿单成功
        FlowBus.with<ProductF>(FlowConst.WISHLIST_ADD_DETAILS).register(this) {

            //如果心愿单显示空布局 移除
            if (viewModel.mAllItemsObserver.value!!.size > 0 && viewModel.mAllItemsObserver.value!![0] is RvNoBoardsEntry) {
                viewModel.mAllItemsObserver.value!!.removeAt(0)
                allItemsPart.getAdapter().notifyItemRemoved(0)
            }

            //将推荐数据添加到board
            viewModel.mAllItemsObserver.value!!.add(
                0,
                RvBoardDetailsItemEntry(
                    wishItem = it,
                    showCheckMode = choiceMode,
                    hasChoice = viewModel.selectAll,
                )
            )
            allItemsPart.getAdapter().notifyItemInserted(0)

            //移除推荐数据
            for ((index, item) in viewModel.mAllItemsObserver.value!!.withIndex()) {
                if (item is RvBoardProductEntry) {
                    if (item.product.id == it.id) {
                        viewModel.mAllItemsObserver.value!!.remove(item)
                        allItemsPart.getAdapter().notifyItemRemoved(index)
                        break
                    }
                }
            }
            allItemsPart.getAdapter().notifyItemRangeChanged(0, allItemsPart.getAdapter().itemCount)
            viewBinding.boardItemNum.text = viewModel.refreshItemsNum(false, 1)
            FlowBus.boolFlowBusNotify(FlowConst.WISHLIST_BOARD_REFRESH)
        }
        //刷新数字
        FlowBus.with<Boolean>(FlowConst.WISHLIST_DETAILS_ITEMS_NUM).register(this) {
            viewBinding.boardItemNum.text = viewModel.refreshItemsNum(false, -1)
        }
        //点加号添加成功
        FlowBus.with<Int>(FlowConst.WISHLIST_ADD_DETAILS_SELECT_PAGE).register(this) {
            toastWishlist("Successfully added to ${boardItemData!!.title} Board")
            viewBinding.boardItemNum.text = viewModel.refreshItemsNum(false, it)
            viewModel.initRefresh(showDialog = true, hasFinish = {
                viewBinding.state.showContent()
                viewBinding.page.finishRefresh()
            })
        }
        //修改心愿单
        FlowBus.with<WishlistRenameEntry>(FlowConst.WISH_DETAILS_CHANGE).register(this) {
            viewModel.reNameF(it) { hasChange ->
                if (hasChange) {
                    FlowBus.boolFlowBusNotify(FlowConst.WISHLIST_BOARD_REFRESH)
                    //标题
                    viewBinding.boardTitle.text = it.title
                    //描述
                    if (it.desc.isNullOrEmpty()) {
                        viewBinding.boardDesc.gone()
                    } else {
                        viewBinding.boardDesc.visible()
                        viewBinding.boardDesc.text = it.desc
                    }
                } else {
                    toastWishlist("change wishlist failed")
                }
            }
        }
        //移动成功
        FlowBus.with<ArrayList<BatchProductArrEntry>>(FlowConst.WISHLIST_DETAILS_MOVE_SUCCESS)
            .register(this) {
                viewBinding.boardItemNum.text =
                    viewModel.refreshItemsNum(false, viewModel.record2Items.size * -it.size)
                viewModel.moveMutiChoiceData(it)
            }
        //显示删除弹窗
        FlowBus.with<Int>(FlowConst.WISH_ALL_ITEMS_SHOW_TOAST_1).register(this) { removedItemNum ->
            toastWishlist("Removed successfully")
            viewBinding.boardItemNum.text = viewModel.refreshItemsNum(false, removedItemNum * -1)
            FlowBus.boolFlowBusNotify(FlowConst.WISHLIST_BOARD_REFRESH)
            if (viewModel.getCurrentItemDataSize() == 0) {
                viewModel.initRefresh(showDialog = true, hasFinish = {
                    viewBinding.state.showContent()
                    viewBinding.page.finishRefresh()
                })
            }
        }

        //显示添加心愿单弹窗
        FlowBus.with<String>(FlowConst.WISH_ALL_ITEMS_SHOW_TOAST_2).register(this) {
            toastWishlist("Successfully added to $it Board")
            FlowBus.boolFlowBusNotify(FlowConst.WISHLIST_BOARD_REFRESH)
        }
    }

    private fun initViewOfUserInfo() {
        //昵称
        viewBinding.boardNick.text = userName
        //头像
//        ImageUtils.loadImage(
//            mContext,
//            headUrl,
//            viewBinding.headerImg,
//            ImageUtils.placeholderAvatarImage,
//            ImageUtils.placeholderAvatarImage
//        )
    }

    /**
     * 更新保存按钮状态
     */
    private fun updateSaveBtn(collected: Boolean) {
        viewBinding.btnSave.isSelected = collected
        viewBinding.btnSave.text = if (collected) "Saved" else "Save"
    }


    /**
     * 多选操作
     */
    fun setMutiView() {
        //多选操作

        //点击all select
        viewBinding.mutiAllChoiceLay.click {
            //点击全选或反选
            allItemsPart.switchAllChoiceImg(selectAllOrReverse = true, 2)
        }

        viewBinding.mutiAllChoiceDel.click {
            //删除弹窗二次确认
            if (viewModel.choiceNum > 0) {
                ConfirmDialog.Builder(mActivity)
                    .setMessage(
                        "Are you sure you want to\n" +
                                "delete ${if (viewModel.choiceNum == 1) "this" else "these"} from your Board?"
                    )
                    .setCancelButton(com.starblink.basic.style.R.string.cancel) { dialog, _ ->
                        dialog.dismiss()
                    }
                    .setSureButton(com.starblink.basic.style.R.string.delete) { dialog, _ ->
                        dialog.dismiss()
                        viewModel.deleteCollItems()
                    }
                    .setCanCancel(true)
                    .create().show()
            } else {
                toastWishlist("Please select at least 1 item")
            }

        }
        viewBinding.mutiAllChoiceAdd.click {

            if (viewModel.choiceNum > 0) {
                var batchPros = arrayListOf<BatchProductArrEntry>()
                viewModel.record2Items.forEach {
                    batchPros.add(
                        BatchProductArrEntry(
                            id = it.wishItem.id ?: "",
                            type = it.wishItem.type,
                            url = it.wishItem.url ?: ""
                        )
                    )
                }
                WishlistAddBottomDialog.showAddListDialog(
                    ActivityStackManage.currentActivity(),
                    batchPros = batchPros,
                    excludeWishlistId = boardItemData?.id,
                    fromWishlistId = viewModel.mWishlistId
                )
            } else {
                toastWishlist("Please select at least 1 item")
            }
        }
    }

    //切换多选模式
    fun intoMutiSelect(choiceMode_1: Boolean) {
        allItemsPart.mutiChange(choiceMode_1)
    }

    //点击右上设置按钮
    private fun clickRightTopSetting() {
        //设置隐藏
        viewBinding.ivSetting.gone()
        //gone 出现
        viewBinding.mutiChoiceMode.visible()
        viewBinding.floatAddBtn.gone()
    }


    //重置全选模式
    private fun resetAllMuti(click: Boolean) {
        viewBinding.ivSetting.visible()
        viewBinding.mutiChoiceMode.gone()
        viewBinding.floatAddBtn.visible()
        if (click) {
            choiceMode = !choiceMode
            intoMutiSelect(choiceMode)
        }

    }

    private fun showOrHideSetting(arr: ArrayList<Any>) {
        var num = 0
        arr.forEach { item ->
            if (item is RvBoardDetailsItemEntry) {
                num++
            }
        }
        if (num == 0 && arr.size > 0 && arr[0] !is RvNoBoardsEntry) {
            arr.add(0, RvNoBoardsEntry())
            viewBinding.ivSetting.gone()
        } else {
            if (viewModel.choiceMode || !isSelf) {
                viewBinding.ivSetting.gone()
            } else {
                viewBinding.ivSetting.visible()
            }
        }
        if (num > 0 && arr[0] is RvNoBoardsEntry) {
            arr.removeAt(0)
        }

        allItemsPart.dataChange(arr)
    }
}